package com.my.library.controller;

import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.my.library.entity.User;
import com.my.library.service.impl.UserServiceImpl;

@Controller
@RequestMapping("/user")
public class UserController extends AbstractController {
	
	@Resource
	private UserServiceImpl userService;
	
	@RequestMapping(value="/login", method={RequestMethod.POST})
	public String login(String name, String pwd, HttpSession session, String dest) {
		StringBuilder msg = new StringBuilder();
		User u = userService.verify(name, pwd, msg);
		if(u == null) {
			session.setAttribute("loginMsg", msg);
			return "redirect:/login.jsp";
		} else {
			session.removeAttribute("loginMsg");
			session.setAttribute("user", u);
			if(dest != null && !"".equals(dest)) {
				return "redirect:" + dest;
			}
			return "redirect:/index.jsp";
		}
	}
	
	@RequestMapping("/logout")
	public String logout(HttpSession session) {
		session.invalidate();
		return "redirect:/login.jsp";
	}
	
	@RequestMapping("/app")
	@ResponseBody
	public List<Map<String, Object>> getapp(HttpSession session) {
		User u = (User) session.getAttribute("user");
		return userService.getAppOfUser(u.getId());
	}
	
	/*@RequestMapping("/")
	public String index() {
		return "index";
	}*/
	
	@RequestMapping(value="/getData", produces="text/xml;charset=UTF-8")
	@ResponseBody()
	public String getData(HttpSession session, int appId) {
		User u = (User) session.getAttribute("user");
		return userService.getData(u.getRoles(), appId);
	}
	
	/*@RequestMapping(value="/add")
	//@ResponseBody
	public void add(User user, PrintWriter writer) {
		System.out.println("UserController.add()");
		writer.print("add success");
	}*/
}
